package com.campus.secondhand.repository.es;

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.client.elc.NativeQueryBuilder;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.stereotype.Repository;

import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.MultiMatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.TermQuery;

import com.campus.secondhand.model.es.UserDocument;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 用户ElasticSearch仓库
 */
@Repository
@RequiredArgsConstructor
@Slf4j
public class UserEsRepository {

    private final ElasticsearchOperations elasticsearchOperations;

    private static final String INDEX_NAME = "user";

    /**
     * 创建或更新用户文档
     *
     * @param document 用户文档
     * @return 操作结果
     */
    public boolean saveUser(UserDocument document) {
        try {
            IndexQuery indexQuery = new IndexQueryBuilder()
                    .withId(document.getId().toString())
                    .withObject(document)
                    .build();

            String documentId = elasticsearchOperations.index(indexQuery, IndexCoordinates.of(INDEX_NAME));
            return documentId != null && !documentId.isEmpty();
        } catch (Exception e) {
            log.error("保存用户到ES失败", e);
            return false;
        }
    }

    /**
     * 搜索用户
     *
     * @param keyword  关键词
     * @param schoolId 学校ID
     * @param from     起始位置
     * @param size     每页大小
     * @return 用户列表
     */
    public List<UserDocument> searchUsers(String keyword, Long schoolId, int from, int size) {
        try {
            // 构建布尔查询
            BoolQuery.Builder boolQueryBuilder = new BoolQuery.Builder();

            // 关键词搜索
            if (keyword != null && !keyword.isEmpty()) {
                boolQueryBuilder.must(
                        new MultiMatchQuery.Builder()
                                .query(keyword)
                                .fields("username", "nickname", "bio")
                                .build()._toQuery());
            }

            // 学校筛选
            if (schoolId != null) {
                boolQueryBuilder.filter(
                        new TermQuery.Builder()
                                .field("schoolId")
                                .value(schoolId)
                                .build()._toQuery());
            }

            // 状态筛选 - 只显示正常用户
            boolQueryBuilder.filter(
                    new TermQuery.Builder()
                            .field("status")
                            .value(1)
                            .build()._toQuery());

            // 构建原生查询
            NativeQuery searchQuery = new NativeQueryBuilder()
                    .withQuery(q -> q.bool(boolQueryBuilder.build()))
                    .withPageable(PageRequest.of(from / size, size))
                    .build();

            // 执行搜索
            SearchHits<UserDocument> searchHits = elasticsearchOperations.search(
                    searchQuery,
                    UserDocument.class,
                    IndexCoordinates.of(INDEX_NAME));

            // 处理结果
            List<UserDocument> results = new ArrayList<>();
            for (SearchHit<UserDocument> hit : searchHits.getSearchHits()) {
                results.add(hit.getContent());
            }

            return results;
        } catch (Exception e) {
            log.error("搜索用户失败", e);
            return List.of();
        }
    }
}